<?php
namespace Weixin\Controller;

use Think\Controller;
use Weixin\Exception\WeixinException;
use Weixin\Model\Category\CategoryModel;
use Weixin\Model\User\UserModel;
use Weixin\Model\User_weixin\UserWeixinModel;
use Weixin\Model\Weixin\WeixinModel;
use Weixin\Request\User\AddUserRequest;
use Weixin\Request\User_weixin\AddUserWeixinRequest;
use Weixin\Request\Weixin\AddWeixinRequest;
use Weixin\Request\Weixin\ChangeSubscribeRequest;
use Weixin\Request\Weixin\FindWeixinRequest;
use Weixin\Request\Weixin\SetCookieRequest;
use Weixin\Service\AddUserService;
use Weixin\Service\AddUserWeixinService;
use Weixin\Service\AddWeixinService;
use Weixin\Service\ChangeSubscribeService;
use Weixin\Service\FindWeixinService;
use Weixin\Service\GetCookieService;
use Weixin\Service\SetCookieService;

class IndexController extends WeixinController
{
    public function test()
    {
        $user = new  UserModel();
        $data = $user->cha2();
        dump($data);

        /*$weixin = new WeixinModel();
        $data = $weixin->cha();
        dump($data);*/
    }

    public function test2()
    {
        $user = new UserModel();
        $result = $user->test2();
        dump($result);
    }

    public function test3()
    {
        $user = new UserModel();
        $result = $user->test3();
        dump($result);
    }

    public function test4()
    {
        $user = new UserModel();
        $result = $user->test4();
        dump($result);
    }

    public function test6()
    {
        $user = new UserModel();
        $result = $user->test6();
        dump($result);
    }

    public function test7()
    {
        $user = new UserModel();
        $result = $user->test7();
        dump($result);
    }

    public function test8()
    {
        $user = new UserModel();
        $result = $user->test8();
        dump($result);
        /*$user = D('user');
        $result = $user->create();*/
        //$user = new UserModel();
        //$result = $user->test8();
        /*dump($result);*/
        // dump(S('data1'));
    }

    public function test9()
    {
        $this->display();
    }

    public function test10()
    {
        $user = new UserModel();
        $data['vote_time'] = 44;
        $result = $user->test9($data);
        dump($result);
    }

    public function test11()
    {
        $user = new UserModel();
        $data['vote_time'] = 11;
        //$data['name'] = 22;
        $result = $user->test11($data);
        dump($result);
    }

    public function test12()
    {
        $data = new stdClass();
        $data->vote_time = 122;
        $user = new UserModel();
        $result = $user->test12($data);
        dump($result);
    }

    public function test13()
    {
        $user = new UserModel();
        dump($user->vote_time);
        $data['vote_time'] = 99;
        $result = $user->test13($data);
        dump($user->vote_time);
        $user->vote_time = 101;
        dump($user->vote_time);
    }

    public function test14()
    {
        $user = new UserModel();
        $data['vote_time'] = 'aa';
        $data['content'] = 122323;
        $result = $user->test14($data);
        dump($result);
    }

    //不创建model直接实例化
    public function new_model()
    {
        /*$new_model=D('new_model');
        $data= $new_model->select();
        dump($data);*/

        /*$user=new UserModel();
        $data=$user->findUser(32);
        dump($data);*/

        $user = new UserModel();
        $data = $user->cha();
        dump($data);
    }


    //D方法 M方法
    public function abc()
    {
        $d_category = D('Weixin/Category');
        //dump($d_category);
        //echo '<br>------------------------------------<br>';
        $m_category = M('Category');
        // dump($m_category);
        $data = $d_category->select();
        dump($data);
    }

    public function test_model()
    {
        $category = new CategoryModel();
        // $data = $category->getDbFields();
        $data = $category->cha();
        dump($data);
    }

    //before、after
    public function run()
    {
        echo 123;
    }

    public function _before_run()
    {
        echo 'before';
    }

    public function _after_run()
    {
        echo 'after';
    }

    //关联关系
    public function mapping()
    {
        //查user表
        //查关联weixin_id
        $id = I('get.id', null);
        $model = new UserModel();
        $data = $model->findUser($id);
        dump($data);

        //查weixin表
        $weixin_id = $data['weixin_id'];
        $model = new WeixinModel();
        $weixin = $model->seekWeixin($weixin_id);
        dump($weixin);
    }

    //U方法
    public function u_action()
    {
        echo U('Weixin/Index/test2?id=1#comment') . '<br>';
        // echo U('Weixin/route/1#comment') . '<br>';
        //  echo U('Weixin/route/1@localhost');
        //echo U('Weixin/route/1');
        //echo $a = U('Weixin/Index/test2?id=1');
        // $this->redirect('Weixin/Index/test2?id=1010');
    }

    //获取变量
    public function get_param()
    {
        // echo I('get.id', null);
        echo I('param.name', null);
    }

    //跳转
    public function tiao()
    {
        // dump($_SERVER['HTTP_REFERER']);
        //$this->success('成功', 'javascript:history.back(-1);', 2);
        $this->error('失败');
    }

    //重定向
    public function chong()
    {
        //$this->redirect('Weixin/Index/test2', array('id' => 22));
        redirect(__ROOT__ . '/Weixin/Index/test2?id=22');
    }

    //输入变量
    public function variable()
    {
        //dump($_SERVER);
        //  echo I('get.id',0) . '<br>' . I('get.name','aa');
        // dump(I('get.name','','htmlspecialchars')) ;
        //dump(I('get.'));

        /*session('aa', 123);
        cookie('bb', 456);
        dump(session('aa'));
        dump(cookie('bb'));
        dump(I('session.'));
        dump(I('cookie.'));
        dump(I('session.aa'));
        dump(I('cookie.bb'));
        dump(I('server.REQUEST_METHOD'));*/

        /*$id = I('id');
        echo $id;*/

        echo I('path.1'); // 输出2013
        echo I('path.2'); // 输出06
        echo I('path.3'); // 输出01
    }

    //success
    public function test_success()
    {
        echo __ROOT__;
        $this->success('success', __ROOT__ . '/Weixin/Index/success_to', 5);
    }

    public function success_to()
    {
        echo 'success_to';
    }

    //过滤
    public function filtrate()
    {
        /* $a = 'tHINK <b>123</b><br>';
         echo $a;
         $a = htmlspecialchars($a);
         echo $a;
         echo '<br>';*/
        //echo $_GET['id'];
        //echo '<br>';
        // echo I('get.id', null,'strip_tags');
        // echo I('get.email', null, 'email');
        /*echo I('get.id',null,'/^\d+$/');
        echo '<br>';
        echo I('get.name',null,'/^[A-Za-z]+$/');*/
        //echo I('get.id', null, false);
        dump(I('get.id'));
        dump(I('get.id/d'));
        dump(I('get.id/s'));
        dump(I('get.id/a'));
        dump(I('get.id/b'));
        dump(I('get.id/f'));
    }

    //判断请求类型
    public function request_type()
    {
        dump(I('server.REQUEST_METHOD'));
        dump(IS_GET);
        dump(IS_POST);
        dump(IS_PUT);
        dump(IS_AJAX);
        dump(IS_DELETE);
    }

    public function _empty($name)
    {
        $this->city($name);
    }

    public function city($name)
    {
        echo '当前城市：' . $name;
    }

    public function test5()
    {
        $this->redirect('Weixin/Index/test3');
    }

    /* public function index($id = 2, $name = 'bb')
     {
         echo $id . $name;
     }*/

    public function read($id)
    {
        echo 'read,' . $id . '!';
    }

    public function write()
    {
        if (isset($_GET['name'])) {
            echo 'name=' . $_GET['name'];
        } else {
            echo 'id=' . $_GET['id'];
        }
    }

    public function verify()
    {
        dump(I('id', null));
        dump($_GET['id']);
    }

    public function totime()
    {
        echo $begin = strtotime('20170602') . '<br>';
        echo strtotime('+1 day 1 hour 1second', $begin) . '<br>';
        echo strtotime('1 day 1 hour 1second', 0);
    }

    public function archive()
    {
        $year = I('year', null);
        $month = I('month', null);
        $day = I('day', null);
        echo $begin = strtotime($year . $month . $day) . '<br>';
        echo $end = strtotime('+1 month', $begin) . '<br>';
        echo ($end - $begin) / 24 / 3600 . '<br>';
        echo (strtotime('+1 month', 0)) / 24 / 3600 . '<br>';

        $str_begin = date('Y-m-d H:i:s', $begin);
        $str_end = date('Y-m-d H:i:s', $end);
        dump($str_begin);
        dump($str_end);

        $map['apply_end_time'] =
            array(
                array('gt', $str_begin),
                array('lt', $str_end)
            );
        $act = M('act')->where($map)->field('name,apply_end_time')->select();
        dump($act);
    }

    public function load_wechat($type = '')
    {
        static $wechat = array();
        $index = md5(strtolower($type));
        if (!isset($wechat[$index])) {
            // 定义微信公众号配置参数（这里是可以从数据库读取的哦）
            $options = array(
                'token' => 'meiyile', // 填写你设定的key
                'appid' => 'wxbb0b2843c24ea073', // 填写高级调用功能的app id, 请在微信开发模式后台查询
                'appsecret' => '94d6a715842eda6f07eb728994e7991d', // 填写高级调用功能的密钥
                'encodingaeskey' => '', // 填写加密用的EncodingAESKey（可选，接口传输选择加密时必需）
                'mch_id' => '', // 微信支付，商户ID（可选）
                'partnerkey' => '', // 微信支付，密钥（可选）
                'ssl_cer' => '', // 微信支付，双向证书（可选，操作退款或打款时必需）
                'ssl_key' => '', // 微信支付，双向证书（可选，操作退款或打款时必需）
                'cachepath' => '', // 设置SDK缓存目录（可选，默认位置在Wechat/Cache下，请保证写权限）
            );
            \Wechat\Loader::config($options);
            $wechat[$index] = \Wechat\Loader::get($type);
        }
        return $wechat[$index];
    }

    public function receive()
    {
        $signature = I('get.signature', null);
        $xml_data = file_get_contents("php://input");
        \Think\Log::record("{$signature}测试日志信息，这是警告级别", 'WARN');
        // include APP_PATH . 'Wechat/Loader.php';

        // $receive = $this->load_wechat('Receive');
        //dump($receive);

        // if ($receive->valid() === FALSE) {
        // 接口验证错误，记录错误日志
        // log_message('ERROR', "微信被动接口验证失败，{$wechat->errMsg}[{$wechat->errCode}]");
        // 退出程序
        //    exit($receive->errMsg);
        // }
    }

    public function oauth()
    {
        include APP_PATH . 'Wechat/Loader.php';

        //获取cookie
        $service = new GetCookieService();
        $response = $service->run();

        if ($response->getItIsNull() == false) {
            //获取用户信息(包括是否关注公众号，必须已关注公众号)
            $openid = $response->getData();
            $user = $this->load_wechat('User');
            $userInfo = $user->getUserInfo($openid);
            $subscribe = $userInfo['subscribe'];

            //根据openid查询用户信息
            $request = new FindWeixinRequest();
            $request->setOpenid($openid);
            $service = new FindWeixinService();
            $response = $service->run($request);
            if ($response->getItIsNull() == false) {
                $data = $response->getData();
            }
            dump($data);

            //判断关注状态是否改变
            if ($data['subscribe'] != $subscribe) {
                //修改关注状态
                $request = new ChangeSubscribeRequest();
                $request->setSubscribe($subscribe);
                $request->setOpenid($openid);
                $service = new ChangeSubscribeService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30003);
                }
            }
        } else {
            //获取oauth
            $oauth = $this->load_wechat('Oauth');

            //获取token
            $token = $oauth->getOauthAccessToken();

            //若获取不到token，则跳转至授权页面
            if (!$token) {
                $url = $oauth->getOauthRedirect("http://" . I("server.HTTP_HOST") . __SELF__, 'meiyile', 'snsapi_base');
                header("location: $url");
                die();
            }

            //获取用户信息(包括是否关注公众号，必须已关注公众号)
            $user = $this->load_wechat('User');
            $userInfo = $user->getUserInfo($token['openid']);
            dump($userInfo);

            //判断是否关注公众号
            if ($userInfo['subscribe'] == 0) {
                //获取授权用户信息
                $oauthUserinfo = $oauth->getOauthUserinfo($token['access_token'], $token['openid']);

                $nickname = $oauthUserinfo["nickname"];
                $headimgurl = $oauthUserinfo["headimgurl"];
                $subscribe = $userInfo["subscribe"];
                //  dump($oauthUserinfo);
            } else {
                $nickname = $userInfo["nickname"];
                $headimgurl = $userInfo["headimgurl"];
                $subscribe = $userInfo["subscribe"];
            }

            //根据openid查询用户信息
            $openid = $token['openid'];
            $request = new FindWeixinRequest();
            $request->setOpenid($openid);
            $service = new FindWeixinService();
            $response = $service->run($request);
            if ($response->getItIsNull() == false) {
                $data = $response->getData();
            }
            dump($data);

            if (isset($data) == false) {
                //添加用户信息
                //添加微信表
                $request = new AddWeixinRequest();
                $request->setOpenid($openid);
                $request->setNickname($nickname);
                $request->setHeadimgurl($headimgurl);
                $request->setSubscribe($subscribe);

                $service = new AddWeixinService();
                $response = $service->run($request);

                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30001);
                } else {
                    $weixin_id = $response->getData();
                }

                //添加用户表
                $request = new AddUserRequest();
                $request->setNickname($nickname);
                $service = new AddUserService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30005);
                } else {
                    $user_id = $response->getData();
                }

                //添加关联表
                $request = new AddUserWeixinRequest();
                $request->setWeixinId($weixin_id);
                $request->setUserId($user_id);
                $service = new AddUserWeixinService();
                $response = $service->run($request);
                if ($response->getItIsNull() == true) {
                    throw new WeixinException(30004);
                }
            } else {
                //判断关注状态是否改变
                $subscribe = $userInfo['subscribe'];
                //dump($subscribe);

                if ($data['subscribe'] != $subscribe) {
                    //修改关注状态
                    $request = new ChangeSubscribeRequest();
                    $request->setSubscribe($subscribe);
                    $request->setOpenid($openid);
                    $service = new ChangeSubscribeService();
                    $response = $service->run($request);
                    if ($response->getItIsNull() == true) {
                        throw new WeixinException(30003);
                    }
                }
            }

            //设置cookie
            $request = new SetCookieRequest();
            $request->setOpenid($token['openid']);
            $service = new SetCookieService();
            $service->run($request);
        }
    }
}